package 反射.T14;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class T14 {

    public static void main(String[] args) throws Exception {

        List<Animal>list=show();
        for (Animal animal : list) {
            System.out.println(animal.toString());
        }

    }
    public static List<Animal> show() throws Exception {
        List<String>list = FileUtils.readLines(new File("反射/T14/dataAnimal.txt"));
        List<Animal> animals = new ArrayList<>();

        for (String s : list) {
            int num = s.indexOf(" ");
            String className = s.substring(0, num);
            String value = s.substring(num+1);
            Class<?> aClass = Class.forName(className);
            Class<?> superclass = aClass.getSuperclass();
            Object obj = aClass.newInstance();
            String[] s1 = value.split(" ");
            for (String s2 : s1) {
                String[] ss = s2.split("=");
                if (ss[0].equals("name")||ss[0].equals("id")){
                    Field df = superclass.getDeclaredField(ss[0]);
                    df.setAccessible(true);
                    df.set(obj,ss[1]);
                }else {
                    Field df = aClass.getDeclaredField(ss[0]);
                    df.setAccessible(true);
                    if (ss[0].equals("age")){
                        df.set(obj,Integer.parseInt(ss[1]));
                    }else {
                        df.set(obj,ss[1]);
                    }
                }
            }
            animals.add((Animal) obj);
        }
        return animals;
    }
}